package com.example.demo.controller;

import com.example.demo.entities.User;
import com.example.demo.server.UserService;
import com.example.demo.util.GeneralResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/users")
    public GeneralResponse books(){
        GeneralResponse response=new GeneralResponse();
        response.setSuccess(true);
        response.setData(userService.getAllUsers());
        return response;
    }
    @PostMapping("/user/add")
    public GeneralResponse add(@RequestParam int id, @RequestParam String name, @RequestParam int pwd, @RequestParam String lesson,@RequestParam String sex){
        User user=new User();
        user.setId(id);
        user.setName(name);
        user.setPwd(pwd);
        user.setLesson(lesson);
        user.setSex(sex);
        GeneralResponse response=new GeneralResponse();
        response.setSuccess(true);
        response.setData(userService.add(user));
        return response;
    }
    @PutMapping("/user/update")
    public GeneralResponse update(@RequestParam int id, @RequestParam String name, @RequestParam int pwd, @RequestParam String lesson,@RequestParam String sex){
        User user=new User();
        user.setId(id);
        user.setName(name);
        user.setPwd(pwd);
        user.setLesson(lesson);
        user.setSex(sex);
        GeneralResponse response=new GeneralResponse();
        response.setSuccess(true);
        response.setData(userService.update(user));
        return response;
    }

    @PostMapping("/user/delete")
    public GeneralResponse delete(@RequestParam int id){
        GeneralResponse response=new GeneralResponse();
        response.setSuccess(true);
        response.setData(userService.deleteById(id));
        return response;
    }
    @GetMapping("/user")
    public GeneralResponse bookById(@RequestParam int id){
        GeneralResponse response=new GeneralResponse();
        response.setSuccess(true);
        List<User> result=new ArrayList<>();
        result.add(userService.getById(id));
        response.setData(result);
        return response;
    }
}
